<template>
  <div class="app-container" v-loading="loading">
    <FaPageHeader>
      <template #title>
        <div class="flex items-center gap-4">
          <Monitor style="width: 1em; height: 1em; vertical-align: middle; display: inline;" />
          <b style="vertical-align: middle;"> 服务器信息</b>
        </div>
      </template>
      <template #description>
        <el-form ref="menuRef" class="mt8" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="服务器名称">
                <span v-if="server.sys">{{ server.sys.computerName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="操作系统">
                <span v-if="server.sys">{{ server.sys.osName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="服务器IP">
                <span v-if="server.sys">{{ server.sys.computerIp }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="系统架构">
                <span v-if="server.sys">{{ server.sys.osArch }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </FaPageHeader>
    <div class="p4">
      <el-row>
        <el-col :span="12" class="card-box">
          <el-divider content-position="left">
            <Cpu style="width: 1em; height: 1em; vertical-align: middle; display: inline;" />
            <b style="vertical-align: middle;"> CPU</b>
          </el-divider>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <thead>
                <tr>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">属性</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">值</div>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">核心数</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="server.cpu">{{ server.cpu.cpuNum }}</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">总使用率</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="server.cpu">{{ server.cpu.used }}%</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">系统使用率</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="server.cpu">{{ server.cpu.sys }}%</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">当前空闲率</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="server.cpu">{{ server.cpu.free }}%</div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-col>

        <el-col :span="12" class="card-box">
          <el-divider content-position="left">
            <Tickets style="width: 1em; height: 1em; vertical-align: middle; display: inline;" />
            <b style="vertical-align: middle;"> 内存</b>
          </el-divider>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <thead>
                <tr>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">属性</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">内存</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">JVM</div>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">总内存</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="memStats">{{ formatBytes(memStats.total, 'GB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats">{{ formatBytes(jvmStats.total, 'MB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">已用内存</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="memStats">{{ formatBytes(memStats.used, 'GB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats">{{ formatBytes(jvmStats.used, 'MB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">剩余内存</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="memStats">{{ formatBytes(memStats.free, 'GB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats">{{ formatBytes(jvmStats.free, 'MB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">使用率</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="memStats" :class="{ 'text-danger': memStats.usage > 80 }">
                      <div class="flex items-center gap-2">
                        <span>{{ formatPercentage(memStats.usage) }}</span>
                      </div>
                    </div>
                    <div class="cell" v-else>--</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats" :class="{ 'text-danger': jvmStats.usage > 80 }">
                      <div class="flex items-center gap-2">
                        <span>{{ formatPercentage(jvmStats.usage) }}</span>
                      </div>
                    </div>
                    <div class="cell" v-else>--</div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-col>


        <el-col :span="24" class="card-box">
          <el-divider content-position="left">
            <CoffeeCup style="width: 1em; height: 1em; vertical-align: middle; display: inline;" />
            <b style="vertical-align: middle;"> Java虚拟机信息</b>
          </el-divider>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;table-layout:fixed;">
              <tbody>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">Java版本</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ jvmStats?.version ?? '--' }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">JDK目录</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ jvmStats?.home ?? '--' }}</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">最大可用内存</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats">{{ formatBytes(jvmStats.max, 'MB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">当前分配</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats">{{ formatBytes(jvmStats.total, 'MB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">已用内存</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats">{{ formatBytes(jvmStats.used, 'MB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">剩余内存</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" v-if="jvmStats">{{ formatBytes(jvmStats.free, 'MB') }}</div>
                    <div class="cell" v-else>--</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">使用率</div>
                  </td>
                  <td class="el-table__cell is-leaf" colspan="3">
                    <div class="cell" v-if="jvmStats">
                      <div class="flex items-center gap-2" :class="{ 'text-danger': jvmStats.usage > 80 }">
                        <span>{{ formatPercentage(jvmStats.usage) }}</span>
                      </div>
                    </div>
                    <div class="cell" v-else>--</div>
                  </td>
                </tr>
                <tr>
                  <td colspan="1" class="el-table__cell is-leaf">
                    <div class="cell">项目路径</div>
                  </td>
                  <td colspan="3" class="el-table__cell is-leaf">
                    <div class="cell">{{ server.sys?.userDir ?? '--' }}</div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-col>

        <el-col :span="24" class="card-box">
          <el-divider content-position="left">
            <FaIcon name="redis" class="menu-item-container-icon size-3 transition-transform group-hover-scale-120" />
            <b style="vertical-align: middle;"> Redis 缓存</b>
          </el-divider>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;table-layout:fixed;">
              <tbody>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">Redis版本</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisInfo.redis_version ?? '--' }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">端口</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisInfo.tcp_port ?? '--' }}</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">运行模式</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisModeLabel }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">客户端连接数</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ formatNumber(redisInfo.connected_clients) }}</div>
                  </td>
                </tr>
                <tr>
                  <td colspan="1" class="el-table__cell is-leaf">
                    <div class="cell">运行时间(天)</div>
                  </td>
                  <td colspan="3" class="el-table__cell is-leaf">
                    <div class="cell">{{ formatNumber(redisInfo.uptime_in_days) }}</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">使用CPU(子进程)</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ formatNumber(redisCpuUsage, 's') }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">使用内存</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisInfo.used_memory_human ?? '--' }}</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">内存配置</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisInfo.maxmemory_human ?? '未限制' }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">AOF</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisInfo.aof_enabled === '1' ? '开启' : '关闭' }}</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">RDB最近状态</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisInfo.rdb_last_bgsave_status ?? '--' }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">Key数量</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ redisDbSize }}</div>
                  </td>
                </tr>
                <tr>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">网络入口/出口</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">
                      {{ formatThroughput(redisInfo.instantaneous_input_kbps, redisInfo.instantaneous_output_kbps) }}
                    </div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">复制/持久化</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">
                      {{ redisInfo.redis_mode === 'standalone' ? 'Master' : (redisInfo.role ?? '--') }}
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-col>
        <el-col :span="24" class="card-box">
          <el-divider content-position="left">
            <MessageBox style="width: 1em; height: 1em; vertical-align: middle; display: inline;" />
            <b style="vertical-align: middle;"> 磁盘状态</b>
          </el-divider>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <thead>
                <tr>
                  <th class="el-table__cell el-table__cell is-leaf">
                    <div class="cell">盘符路径</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">文件系统</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">盘符类型</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">总大小</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">可用大小</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">已用大小</div>
                  </th>
                  <th class="el-table__cell is-leaf">
                    <div class="cell">已用百分比</div>
                  </th>
                </tr>
              </thead>
              <tbody v-if="server.disk">
                <tr v-for="(d, index) in server.disk" :key="index">
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ d.dirName }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ d.sysTypeName }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ d.typeName }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ d.total }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ d.free }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell">{{ d.used }}</div>
                  </td>
                  <td class="el-table__cell is-leaf">
                    <div class="cell" :class="{ 'text-danger': d.usage > 80 }">
                      <div class="flex items-center gap-2">
                        <span>{{ formatPercentage(d.usage, 2) }}</span>
                        <el-progress
                          :percentage="Number(d.usage ?? 0)"
                          :status="getProgressStatus(d.usage)"
                          :stroke-width="8"
                          :show-text="false"
                          class="flex-1"
                        />
                      </div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import apiServer from '@/api/monitor/server'

const { proxy } = getCurrentInstance()
const loading = ref(false)
const server = ref({
  sys: {},
  cpu: {},
  mem: null,
  jvm: null,
  disk: [],
  redis: null
})

const formatNumber = (value, suffix = '') => {
  if (value === undefined || value === null || value === '') {
    return '--'
  }
  return `${value}${suffix}`
}

const formatBytes = (value, unit = 'GB', precision = 2) => {
  if (value === undefined || value === null) {
    return '--'
  }
  const bytes = Number(value)
  if (Number.isNaN(bytes)) {
    return '--'
  }
  const divider = unit === 'MB' ? 1024 ** 2 : 1024 ** 3
  return `${(bytes / divider).toFixed(precision)} ${unit}`
}

const formatPercentage = (value, precision = 2) => {
  if (value === undefined || value === null || value === '') {
    return '--'
  }
  const num = Number(value)
  if (Number.isNaN(num)) {
    return '--'
  }
  return `${num.toFixed(precision)}%`
}

const getProgressStatus = value => {
  const percent = Number(value) || 0
  if (percent >= 85) return 'exception'
  if (percent >= 60) return 'warning'
  return 'success'
}

const memStats = computed(() => {
  const mem = server.value?.mem
  if (!mem) return null
  const total = Number(mem.total ?? 0)
  const used = mem.used !== undefined ? Number(mem.used) : total - Number(mem.free ?? 0)
  const free = mem.free !== undefined ? Number(mem.free) : Math.max(total - used, 0)
  const usage = total ? (used / total) * 100 : 0
  return { total, used, free, usage }
})

const jvmStats = computed(() => {
  const jvm = server.value?.jvm
  if (!jvm) return null
  const total = Number(jvm.total ?? 0)
  const free = Number(jvm.free ?? 0)
  const max = Number(jvm.max ?? total)
  const used = Math.max(total - free, 0)
  const usage = total ? (used / total) * 100 : 0
  return {
    ...jvm,
    total,
    free,
    max,
    used,
    usage
  }
})

const redisInfo = computed(() => server.value?.redis?.info ?? {})
const redisDbSize = computed(() => server.value?.redis?.dbSize ?? '--')
const redisCpuUsage = computed(() => {
  const val = redisInfo.value.used_cpu_user_children
  if (val === undefined || val === null || val === '') return null
  const num = Number(val)
  if (Number.isNaN(num)) return null
  return num.toFixed(2)
})
const redisModeLabel = computed(() => {
  const mode = redisInfo.value.redis_mode
  if (!mode) return '--'
  return mode === 'standalone' ? '单机' : '集群'
})

const formatThroughput = (input, output) => {
  if (input === undefined || output === undefined) return '--'
  return `${input ?? 0} kbps / ${output ?? 0} kbps`
}

const fetchServer = async () => {
  try {
    loading.value = true
    const { data } = await apiServer.getServer()
    server.value = data || {}
  } catch (error) {
    console.error('加载服务器信息失败', error)
    proxy?.$message?.error?.('服务器信息获取失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(fetchServer)
</script>
